import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
// import 'package:image_saver/image_saver.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import '../base/Constant.dart';
import '../util/AppSaveInfoUtil.dart';
import '../util/LoadingUtil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_view/photo_view_gallery.dart';
import '../http/Api.dart';

class PreviewImagesWidget extends StatefulWidget {
  ///图片Lst
  final List<String> imageList;

  ///初始展示页数。默认0
  int initialPage;

  ///选中的页的点的颜色
  Color checkedColor;

  ///未选中的页的点的颜色
  Color uncheckedColor;

  PreviewImagesWidget(this.imageList,
      {this.initialPage = 0,
      this.checkedColor = Colors.white,
      this.uncheckedColor = Colors.grey});

  @override
  _PreviewImagesWidgetState createState() =>
      _PreviewImagesWidgetState(initialPage: initialPage);
}

class _PreviewImagesWidgetState extends State<PreviewImagesWidget> {
  PageController pageController;
  int nowPosition;
  int initialPage;
  List<Widget> dotWidgets;

  _PreviewImagesWidgetState({this.initialPage = 0});

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    nowPosition = initialPage;
    pageController = PageController(initialPage: initialPage);
    _initData();
  }

  void _initData() {
    dotWidgets = [];
    if (widget.imageList.length > 1) {
      for (int i = 0; i < widget.imageList.length; i++) {
        dotWidgets.add(_buildDots(i));
      }
    }
  }

  Widget _buildDots(int index) => Container(
        margin: EdgeInsets.all(5),
        child: ClipOval(
          child: Container(
            color: index == nowPosition
                ? widget.checkedColor
                : widget.uncheckedColor,
            width: 5.0,
            height: 5.0,
          ),
        ),
      );

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => Navigator.of(context).pop(),
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: <Widget>[
          PhotoViewGallery.builder(
            onPageChanged: (index) {
              setState(() {
                nowPosition = index;
                _initData();
              });
            },
            scrollPhysics: const BouncingScrollPhysics(),
            builder: (BuildContext context, int index) {
              return PhotoViewGalleryPageOptions(
                imageProvider: NetworkImage(
                    widget.imageList[index].contains("http")
                        ? widget.imageList[index]
                        : Api.ImgBaseUrl + widget.imageList[index]),
              );
            },
            itemCount: widget.imageList.length,
            pageController: pageController,
          ),
          Container(
            margin: EdgeInsets.only(bottom: 10),
            child: Wrap(
              children: dotWidgets,
            ),
          ),
          // Positioned(
          //     bottom: 50,
          //     child: GestureDetector(
          //       child: Container(
          //         padding: EdgeInsets.fromLTRB(30, 10, 30, 10),
          //         decoration: BoxDecoration(
          //             borderRadius: BorderRadius.circular(30),
          //             border: Border.all(color: white, width: 1)),
          //         child: Text('保存到本地',
          //             style: TextStyle(
          //                 color: white,
          //                 fontSize:
          //                     ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
          //                 decoration: TextDecoration.none)),
          //       ),
          //       onTap: () async {
          //         Directory dic;
          //         if (Platform.isAndroid) {
          //           dic = await getExternalStorageDirectory();
          //         } else {
          //           dic = await getApplicationDocumentsDirectory();
          //         }
          //         String imgPath = widget.imageList[pageController.page.floor()]
          //                 .contains("http")
          //             ? widget.imageList[pageController.page.floor()]
          //             : Api.ImgBaseUrl +
          //                 widget.imageList[pageController.page.floor()];
          //         downloadFile(
          //             imgPath,
          //             dic.path +
          //                 "/" +
          //                 DateTime.now().millisecondsSinceEpoch.toString() +
          //                 ".png");
          //       },
          //     ))
        ],
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    pageController.dispose();
  }

  /*
   * 下载文件
   */
  downloadFile(urlPath, savePath) async {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return new NetLoadingDialog(
              loadingText: "保存中...",
              bgColor: Color.fromARGB(255, 0, 0, 0),
              requestCallBack: null,
              outsideDismiss: false,
            );
          });
    Dio dio = Dio();
    dio.options.responseType = ResponseType.bytes;
    var response = await dio.get(urlPath);
    // File savedFile = await ImageSaver.toFile(fileData: Uint8List.fromList(response.data));
    final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
    // print(result.path);
    if (result != null) Fluttertoast.showToast(msg: "保存成功");
    Navigator.of(context).pop(1);
  }
}
